<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="gatewayQueryForm" :inline="true">
        <el-form-item :label="$t('gateway.gatewayName')" prop="id">
          <el-select
              v-model="gatewayQueryForm.id"
              :placeholder="
              $t('common.placeholderSelect') + $t('gateway.gatewayName')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in gatewayList"
                :key="index"
                :label="locale ? item.gatewayCnName : item.gatewayEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}
          </el-button>
          <el-button @click="addgateway" type="primary" icon="Plus">{{
              $t("common.add")
            }}
          </el-button>

          <el-button @click="getAllMqttConnectInfo" type="primary" icon="Search">Mqtt获取所有连接信息
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="gatewayForm"
        :form-rules="gatewayRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <!--        <el-form-item :label="$t('gateway.sn')" prop="sn">-->
        <!--          <el-input-->
        <!--              v-model="gatewayForm.sn"-->
        <!--              :placeholder="-->
        <!--              $t('common.placeholderInput') + $t('gateway.sn')-->
        <!--            "-->
        <!--              clearable-->
        <!--              maxLength="50"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item :label="$t('gateway.gatewayCnName')" prop="gatewayCnName">
          <el-input
              v-model="gatewayForm.gatewayCnName"
              :placeholder="
              $t('common.placeholderInput') + $t('gateway.gatewayCnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('gateway.gatewayEnName')" prop="gatewayEnName">
          <el-input
              v-model="gatewayForm.gatewayEnName"
              :placeholder="
              $t('common.placeholderInput') + $t('gateway.gatewayEnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('gateway.gatewayFileId')" prop="fileServerId">
          <el-select
              v-model="gatewayForm.fileServerId"
              :placeholder="
              $t('common.placeholderSelect') + $t('gateway.gatewayFileId')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in sftpServerList"
                :key="index"
                :label="locale ? item.sftpServerCnName : item.sftpServerEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('gateway.gatewayMqttId')" prop="mqttServerId">
          <el-select
              v-model="gatewayForm.mqttServerId"
              :placeholder="
              $t('common.placeholderSelect') + $t('gateway.gatewayMqttId')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in mqttServerList"
                :key="index"
                :label="locale ? item.mqttServerCnName : item.mqttServerEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('gateway.channleAssociated')" prop="protId">
          <el-select
              v-model="gatewayForm.protId"
              :placeholder="
              $t('common.placeholderSelect') + $t('gateway.channleAssociated')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in channelList"
                :key="index"
                :label="locale ? item.channelCnName : item.channelEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('gateway.gatewayEnable')" prop="isEnable">
          <el-select
              v-model="gatewayForm.isEnable"
              :placeholder="
              $t('common.placeholderSelect') + $t('gateway.gatewayEnable')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in isEnableList"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          >
            <!-- 网关管理标题 -->
            <div class="station-management-header">
              <div class="title-wrapper">
                <el-icon class="title-icon">
                  <OfficeBuilding/>
                </el-icon>
                <h3 class="station-title">{{ $t('gateway.gatewayManagement') }}</h3>
              </div>
              <div class="station-stats">
                <span class="stat-item">
                  <span class="stat-label">{{ $t('gateway.gatewayNum') }}：</span>
                  <span class="stat-value">{{ total }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">{{ $t('gateway.gatewayEnableNum') }}：</span>
                  <span class="stat-value">{{ enabledStations }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">{{ $t('gateway.stationAssociated') }}：</span>
                  <span class="stat-value">{{ getstationNameBystationId(stationId) }}</span>
                </span>

              </div>
            </div>
            <!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />
              <el-table-column
                  :label="$t('gateway.sn')"
                  align="center"
                  prop="sn"
              />
              <el-table-column
                  :label="$t('gateway.gatewayCnName')"
                  align="center"
                  prop="gatewayCnName"
              />
              <el-table-column
                  :label="$t('gateway.gatewayEnName')"
                  align="center"
                  prop="gatewayEnName"
              />
              <el-table-column
                  :label="$t('gateway.gatewayFileId')"
                  align="center"
                  prop="fileServerId"
              >
                <template #default="scope">
                  {{
                    getsftpServerNameBysftpServerId(scope.row.fileServerId)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('gateway.gatewayMqttId')"
                  align="center"
                  prop="mqttServerId"
              >
                <template #default="scope">
                  {{
                    getMqttServerNameByMqttServerId(scope.row.mqttServerId)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('gateway.channleAssociated')"
                  align="center"
                  prop="protType"
              >
                <template #default="scope">
                  {{
                    getChannelNameByProtId(scope.row.protId)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="300"
                  fixed="right"
              >
                <template #default="scope">
                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updategateway(scope.row)"
                  >{{ $t("common.edit") }}
                  </el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="deletegateway(scope.row)"
                  >{{ $t("common.delete") }}
                  </el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="touchSubscribe(scope.row)"
                  >触发订阅
                  </el-button
                  >
                  <el-dropdown>
                    <el-button
                        style="margin-top: 3px;margin-left: 10px"
                        type="default"
                        link

                    >{{ $t("common.point") }}
                    </el-button
                    >
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="goPoint(scope.row, 'YC')">{{ $t("common.yc") }}</el-dropdown-item>
                        <el-dropdown-item @click="goPoint(scope.row, 'YX')">{{ $t("common.yx") }}</el-dropdown-item>
                        <el-dropdown-item @click="goPoint(scope.row, 'YT')">{{ $t("common.yt") }}</el-dropdown-item>
                        <el-dropdown-item @click="goPoint(scope.row, 'YK')">{{ $t("common.yk") }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <el-button
                      type="warning"
                      link
                      icon="Setting"
                      @click="goSnConf(scope.row)"
                  >{{ $t("common.snConf") }}
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="gatewayQueryForm.pageNum"
                  v-model:page-size="gatewayQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import moment from "moment";
import {
  getgatewayListApi,
  getgatewayPageApi,
  addgatewayApi,
  updategatewayApi,
  delgatewayApi
} from "@/api/ems/gateway/gateway.ts";
import {
  validateSwitchMqttApi, switchSwitchMqttApi,
  protocolmqtt,gdevcom
} from "@/api/mqtt/mqttSwitch.ts"
import {
  getchannelListApi
} from "@/api/ems/channel/channel.ts";
import {
  getmqttServerConfPageApi,
} from "@/api/ems/mqttServerConf/mqttServerConf";
import {
  getsftpServerConfPageApi,
} from "@/api/ems/sftpServerConf/sftpServerConf"
import {
  getstationListApi,
} from "@/api/ems/station/station.ts";
import {getValidMqttConnectApi} from "@/api/mqtt/validconnect.ts"
import {getEnumListByType} from "@/api/enums";
import {EmsCommonEnums} from "@/enum/common/EmsCommonEnums"
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import {useI18n} from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import {reactive, ref, onMounted, onUnmounted, watch, nextTick, computed} from "vue";
import {useRoute, useRouter} from "vue-router";
import {OfficeBuilding} from "@element-plus/icons-vue";

const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示
const router = useRouter();
const route = useRoute();
const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const {t} = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 场站查询表单数据
const gatewayQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  id: "", // 场站Id
  stationId: null,//场站ID
});
const enabledStations = computed(() => {
  if (!tableData.value) return 0;
  return tableData.value.filter(item => item.isEnable === 1).length;
});
// 2. 场站新增表单数据
const gatewayForm = reactive({
  gatewayCnName: "", // 场站中文名称
  gatewayEnName: "", // 场站英文名称
  fileServerId: "",  // 文件服务器Ip
  mqttServerId: "",  // mqtt服务器Ip
  sn: "",//网关
  pkey: "",
  protId: null,  // 协议ID
  stationId: null,//场站ID
  comment: "", //场站Ip
  isEnable: null, //场站是否可用
  gatewayStatus: null, //场站状态
});
// 3. 标签表单校验规则
const gatewayRules = reactive({
  sn: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("gateway.inputRule"), trigger: "blur"},
  ],
  gatewayCnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  gatewayEnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  mqttServerId: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
  protId: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
  isEnable: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
});
//网关列表
const gatewayList = ref([]);
//可用列表枚举
const isEnableList = ref([]);
//服务器列表
const mqttServerList = ref([]);
//sftp服务列表
const sftpServerList = ref([])
//场站列表
const stationList = ref([]);
//协议列表
const channelList = ref([]);
//获取mqtt服务器配置枚举列表
const getEnumListByTypes = async (type) => {
  let res = await getEnumListByType({type: type});
  if (type == EmsCommonEnums.CommonEnable) {
    isEnableList.value = res.data;
  }
}
//根据场站ID获取场站名称
const getstationNameBystationId = (id) => {
  let res = "";
  stationList.value?.forEach(item => {
    if (item.id == id) {
      res = locale ? item.stationCnName : item.stationEnName;
    }
  })
  return res;
}
const swicthSwitchMqtt = () => {
  switchSwitchMqttApi({newMqttServerId: gatewayForm.mqttServerId, gatewayId: gatewayForm.id}).then((res) => {
  });
}
//
const getAllMqttConnectInfo = () => {
  getValidMqttConnectApi().then((res) => {
  });

}
//获取协议列表
const getChannelList = () => {
  getchannelListApi().then((res) => {
    channelList.value = res.data;
  });
};
//获取场站列表
const getStationList = () => {
  getstationListApi().then((res) => {
    stationList.value = res.data;
  });
};
//查询
const search = () => {
  getSelectPage();
};
const handleSizeChange = (val) => {
  gatewayQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  gatewayQueryForm.pageNum = val;
  getSelectPage();
};
const getSelectPage = () => {
  getgatewayPageApi(gatewayQueryForm).then((res) => {
    tableData.value = res.data.records;
    total.value = res.data.total;
  });
};
const getgatewayList = () => {
  getgatewayListApi().then((res) => {
    gatewayList.value = res.data;
  });
};

// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addgateway = () => {
  dialogVisible.value = true;
  Object.assign(gatewayForm, {
    id: null,
    gatewayCnName: "", // 场站中文名称
    gatewayEnName: "", // 场站英文名称
    fileServerId: "",  // 文件服务器Ip
    mqttServerId: "",  // mqtt服务器Ip
    sn: "",//网关
    pkey: "",
    stationId: stationId.value,//场站ID
    protId: null,  // 协议ID
    comment: "", //场站Ip
    isEnable: null, //场站是否可用
    gatewayStatus: null, //场站状态
  });
  gatewayForm.sn = "sn" + moment().format("YYYYMMDDHHmmss");
  gatewayForm.pkey = "pkey" + moment().format("YYYYMMDDHHmmss");
  dialogTitle.value = t("gateway.gatewayAdd");
};
//修改调出弹框
const gatewayId = ref();
const updategateway = (row) => {
  dialogTitle.value = t("gateway.gatewayUpdate");
  dialogVisible.value = true;
  gatewayId.value = row.id;
  Object.assign(gatewayForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};

//mqtt服务器列表
const getmqttServerList = () => {
  getmqttServerConfPageApi({pageNum: 1, pageSize: 1000}).then((res) => {
    mqttServerList.value = res.data.records;
  });
};
//mqtt服务器列表
const getsftpServerList = () => {
  getsftpServerConfPageApi({pageNum: 1, pageSize: 1000}).then((res) => {
    sftpServerList.value = res.data.records;
  });
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("gateway.gatewayAdd")) {
    addgatewayApi(gatewayForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;

      } else {
        ElMessage.success(t("common.error"));
      }
    });
  } else {
    updategatewayApi(Object.assign(gatewayForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
        validateSwitchMqttApi({newMqttServerId: gatewayForm.mqttServerId, gatewayId: gatewayForm.id}).then((msg) => {
          if (msg.data.valid) {
            swicthSwitchMqtt()
          }
        })
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  }
};
//跳转网关页面
const goPoint = (row, type) => {
  if (type == 'YC') {
    router.push({path: "/stationMangement/pointYc", query: {gatewayId: row.id}})
  }
  if (type == 'YX') {
    router.push({path: "/stationMangement/pointYx", query: {gatewayId: row.id}})
  }
  if (type == 'YT') {
    router.push({path: "/stationMangement/pointYt", query: {gatewayId: row.id}})
  }
  if (type == 'YK') {
    router.push({path: "/stationMangement/pointYk", query: {gatewayId: row.id}})
  }

}
const goSnConf = (row) => {
  router.push({path: "/stationMangement/snConf", query: {gatewayId: row.id, pkey: row.pkey, sn: row.sn}})
}
//删除数据
const deletegateway = (row) => {
  ElMessageBox.confirm(
      `是否确认删除`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
  ).then(() => {
    delgatewayApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};
//根据ID获取协议类型名称
const getChannelNameByProtId = (id) => {
  let res = "";
  channelList.value?.forEach(item => {
    if (item.id == id) {
      res = locale ? item.channelCnName : item.channelEnName;
    }
  })
  return res;
}
const touchSubscribe = (row) => {
  protocolmqtt({gatewayId: row.id}).then((res) => {
  })
  // const intervalId = setInterval(() => {
  //   gdevcom().then((res) => {
  //     // 处理gdevcom的返回结果
  //     console.log("执行结果:", res);
  //   }).catch((err) => {
  //     // 捕获可能的错误，避免循环中断
  //     console.error("执行出错:", err);
  //   });
  // }, 1000); // 1000毫秒 = 1秒
}
//根据ID获取服务器名称
const getMqttServerNameByMqttServerId = (id) => {
  let res = "";
  mqttServerList.value?.forEach(item => {
    if (item.id == id) {
      res = locale ? item.mqttServerCnName : item.mqttServerEnName;
    }
  })
  return res;
}
//根据ID获取服务器名称
const getsftpServerNameBysftpServerId = (id) => {
  let res = "";
  sftpServerList.value?.forEach(item => {
    if (item.id == id) {
      res = locale ? item.sftpServerCnName : item.sftpServerEnName;
    }
  })
  return res;
}
//场站ID（路由跳转的参数ID）
const stationId = ref();
onMounted(() => {
  stationId.value = route.query.stationId;
  gatewayQueryForm.stationId = stationId.value;
  gatewayForm.stationId = stationId.value;
  getStationList();
  getSelectPage();
  getgatewayList();
  getmqttServerList();
  getsftpServerList();
  getChannelList();
  getEnumListByTypes(EmsCommonEnums.CommonEnable);
});
onUnmounted(() => {
});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}

.app-container {
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .station-management-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    .title-wrapper {
      display: flex;
      align-items: center;
      gap: 12px;

      .title-icon {
        font-size: 24px;
        color: #ffffff;
      }

      .station-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #ffffff;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .station-stats {
      display: flex;
      gap: 24px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 12px;
        background: rgba(255, 255, 255, 0.15);
        border-radius: 20px;
        backdrop-filter: blur(10px);

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }

        .stat-value {
          font-size: 16px;
          font-weight: 600;
          color: #ffffff;
        }
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .station-management-header {
      flex-direction: column;
      gap: 16px;
      text-align: center;

      .station-stats {
        justify-content: center;
      }
    }
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
